<?php

namespace app\api\controller;

use app\common\controller\Frontend;
use app\common\enum\fp\PostType;
use app\common\library\token\TokenExpirationException;
use app\common\model\User;
use app\logic\fp\PostCommentLogic;
use app\logic\fp\PostLikeLogic;
use app\logic\fp\PostLogic;
use app\logic\language\LangLogic;
use app\logic\user\FollowLogic;
use app\logic\user\UserLogic;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use think\facade\Config;
use think\facade\Log;
use Throwable;

class Index extends Frontend
{
    protected array $noNeedLogin = ['index'];

    public function initialize(): void
    {
        parent::initialize();
    }

    /**
     * 前台和会员中心的初始化请求
     * @throws Throwable
     */
    public function index(): void
    {
        if (!$this->auth->isLogin()) {
            // 若是从前台会员中心内发出的请求，要求必须登录，否则会员中心异常
            $requiredLogin = $this->request->get('requiredLogin/b', false);
            if ($requiredLogin) {

                // 触发可能的 token 过期异常
                try {
                    $token = get_auth_token(['ba', 'user', 'token']);
                    $this->auth->init($token);
                } catch (TokenExpirationException) {
                    $this->error(__('Token expiration'), [], 409);
                }

                $this->error(__('Please login first'), [
                    'type' => $this->auth::NEED_LOGIN
                ], $this->auth::LOGIN_RESPONSE_CODE);
            }
        }

        $preset_payment_amounts = get_sys_config('preset_payment_amounts');
        if (!empty($preset_payment_amounts)) {
            $preset_payment_amounts = array_filter(explode(',', $preset_payment_amounts));
            $preset_payment_amounts = array_map(function ($item) {
                return (int)$item;
            }, $preset_payment_amounts);
        } else {
            $preset_payment_amounts = [];
        }

        $this->success('', [
            'site' => [
                'siteName' => get_sys_config('site_name'),
                'recordNumber' => get_sys_config('record_number'),
                'version' => get_sys_config('version'),
                // 'cdnUrl' => full_url(),
                //'upload' => keys_to_camel_case(get_upload_config(), ['max_size', 'save_name', 'allowed_suffixes', 'allowed_mime_types']),
                'socialiteLoginSwitch' => Config::get('socialite.switch')
            ],
//            'openMemberCenter' =>  Config::get('buildadmin.open_member_center'),
            'userInfo' => $this->auth->getUserInfo(),
            'language' => LangLogic::getLangList(),
            'pay' => [
                'preset_payment_amounts' => $preset_payment_amounts
            ]
        ]);
    }

    /**
     * 首页发现动态
     */
    public function dynamic()
    {
        // 获取请求中的查询条件
        $page = $this->request->param('page');
        $size = (int)$this->request->param('size');
        $size = $size ?: 15;
        $page = $page ?: 1;
        if ($size > 15 || $size < 0) {
            $size = 15;
        }
        $params['size'] = $size;
        $params['from'] = ($page - 1) * $params['size'];
        $params['filter'] = [
            ['term' => ['type' => PostType::Featured->value]]
        ];
        try {
            $result = PostLogic::getInstance()->all($params);
            $result['list'] = array_map(function ($item) {
                $item['is_like'] = PostLikeLogic::getInstance()->isLike($item['id'], $this->auth->id);
                $item['like_count'] = PostLikeLogic::getInstance()->getLikeCount($item['id'], $item['user_id']);
                $item['comment_count'] = PostCommentLogic::getInstance()->getCommentCount($item['id']);
                $item['tips'] = UserLogic::getInstance()->tips($item['user_id']);
                $user = User::initModel()->where('id', $item['user_id'])->field('is_creator,avatar, vip, vip_expire')->find()->toArray();
                if ($user['vip_expire'] < time()) {
                    $user['vip'] = 0;
                }
                unset($user['vip_expire']);
                $item['user'] = array_merge($user, $item['user']);
                $item['user']['is_creator'] = (int)$user['is_creator'];

                $item['media'] = PostLogic::getInstance()->mediaSignUrl($item['media'], true);

                $item['content'] =  nl2br(htmlspecialchars($item['content'], ENT_QUOTES), false);

                return $item;
            }, $result['list']);
        } catch (\RuntimeException $e) {
            $this->error($e->getMessage());
        } catch (ClientResponseException $e) {
            if ($e->getCode() === 404) {
                $this->error(__('no data'));
            }
            $this->error($e->getMessage());
        } catch (\Throwable $exception) {
            Log::channel('my')->error($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
            // 如果发生异常，捕获并显示错误信息
            $this->error(__('server error'));
        }

        // 查询成功后，调用成功方法处理查询结果
        $this->success('', $result);

    }

    /**
     * 获取用户的关注列表
     * @return void
     */
    public function follow()
    {

        $limit = (int)$this->request->param('size');
        if ($limit > 15 || $limit < 0) {
            $limit = 15;
        }
        try {
            $result = FollowLogic::getInstance()->myFollow($this->auth->id, $limit);
        }catch (\Throwable $exception) {
            $message = config('app.env') != 'prod' ? $exception->getMessage().PHP_EOL . $exception->getTraceAsString() : __('server error');
            Log::channel('my')->error($exception->getMessage() . PHP_EOL . $exception->getTraceAsString());
            $this->error($message);
        }

        $this->success('', $result);
    }
}